package servlet;

import com.sun.xml.bind.v2.TODO;
import entity.Address;
import entity.Cart;
import service.CartService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@WebServlet("/CartServlet")
public class CartServlet extends HttpServlet {
    private CartService cartService = new CartService();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Cart> cartItems = null;
        try {
            HashMap<String,String> user =  (HashMap<String, String>) request.getSession().getAttribute("user");
            if(user==null){
                request.getRequestDispatcher("login.jsp").forward(request,response);
                return;
            }
            int userId = Integer.parseInt(user.get("userId"));// 从会话中获取用户ID
            cartItems = cartService.getCartItems(userId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        double totalPrice = cartService.calculateTotalPrice(cartItems);
        double shippingFee = 5.0; //固定运费
        double payableAmount = totalPrice + shippingFee;

        request.setAttribute("cartItems", cartItems);
        request.setAttribute("totalPrice", totalPrice);
        request.setAttribute("shippingFee", shippingFee);
        request.setAttribute("payableAmount", payableAmount);

        request.getRequestDispatcher("/cart.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        String itemId = request.getParameter("itemId");
        System.out.println(action);
        System.out.println(itemId);
        try {
            if ("addItem".equals(action)) {
                HashMap<String,String> user =  (HashMap<String, String>) request.getSession().getAttribute("user");
                if(user==null){
                    request.getRequestDispatcher("login.jsp").forward(request,response);
                    return;
                }
                int userId = Integer.parseInt(user.get("userId"));// 从会话中获取用户ID
                int productId = Integer.parseInt(request.getParameter("itemId"));
                int quantity = Integer.parseInt(request.getParameter("quantity"));
                cartService.addItem(userId, productId, quantity);
                response.getWriter().write("{\"status\": \"success\", \"message\": \"商品已添加到购物车！\"}");
            } else if ("updateQuantity".equals(action)) {
                int delta = Integer.parseInt(request.getParameter("delta"));
                if (itemId == null || delta == 0) {
                    throw new IllegalArgumentException("参数不完整或非法！");
                }
                cartService.updateQuantity(itemId, delta);
                response.getWriter().write("{\"status\": \"success\", \"message\": \"商品数量更新成功！\"}");
            } else if ("deleteItem".equals(action)) {
                if (itemId == null) {
                    throw new IllegalArgumentException("商品ID不能为空！");
                }
                cartService.deleteItem(itemId);
                response.getWriter().write("{\"status\": \"success\", \"message\": \"商品删除成功！\"}");
            } else if ("moveToFavorites".equals(action)) {
                if (itemId == null) {
                    throw new IllegalArgumentException("商品ID不能为空！");
                }
                cartService.moveToFavorites(itemId);
                response.getWriter().write("{\"status\": \"success\", \"message\": \"商品已移入收藏夹！\"}");
            } else if ("batchDeleteItems".equals(action)) {
                String[] itemIds = request.getParameterValues("itemIds");
                if (itemIds == null || itemIds.length == 0) {
                    throw new IllegalArgumentException("请选择要删除的商品！");
                }
                cartService.batchDeleteItems(Arrays.asList(itemIds));
                response.getWriter().write("{\"status\": \"success\", \"message\": \"批量删除成功！\"}");
            } else if ("checkout".equals(action)) {
                // 去结算逻辑
                handleCheckout(request, response);
            } else {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("{\"status\": \"error\", \"message\": \"未知操作！\"}");
            }
        } catch (IllegalArgumentException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("{\"status\": \"error\", \"message\": \"" + e.getMessage() + "\"}");
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("{\"status\": \"error\", \"message\": \"服务器内部错误，请稍后重试！\"}");
        }
    }

    private void handleCheckout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            HashMap<String,String> user =  (HashMap<String, String>) request.getSession().getAttribute("user");
            if(user==null){
                request.getRequestDispatcher("login.jsp").forward(request,response);
                return;
            }
            int userId = Integer.parseInt(user.get("userId"));// 从会话中获取用户ID
            // 获取购物车数据
            List<Cart> cartItems = cartService.getCartItems(userId);

            if (cartItems == null || cartItems.isEmpty()) {
                response.sendRedirect("/cart.jsp");
                return;
            }

            // 获取收货地址
            Address address = cartService.getDefaultAddress(userId);

            // 如果收货地址为空，提示用户添加地址
            if (address == null) {
                request.setAttribute("errorMessage", "未找到收货地址，请添加收货地址！");
                request.getRequestDispatcher("/cart.jsp").forward(request, response);
                return;
            }

            // 计算总价和运费
            double totalPrice = cartService.calculateTotalPrice(cartItems);
            double shippingFee = 5.0; // 示例：固定运费
            double payableAmount = totalPrice + shippingFee;

            // 设置数据到请求属性
            request.setAttribute("address", address);
            request.setAttribute("cartItems", cartItems);
            request.setAttribute("totalPrice", totalPrice);
            request.setAttribute("shippingFee", shippingFee);
            request.setAttribute("payableAmount", payableAmount);

            // 转发到结算页面
            request.getRequestDispatcher("/checkout.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误，请稍后再试！");
        }
    }

}
